<template>
  <div class="patient-records-container">
    <!-- 头部区域 -->
    <div class="header">
      <h2><el-icon><Document /></el-icon> 我的病历记录</h2>
      <div class="search-box">
        <el-input
            v-model="searchQuery"
            placeholder="搜索病历..."
            clearable
            @clear="resetSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 病历列表 -->
    <div class="record-list">
      <el-card
          v-for="record in filteredRecords"
          :key="record.recordId"
          class="record-card"
          @click="viewRecordDetail(record)"
      >
        <div class="card-header">
          <span class="record-title">{{ record.department }}就诊记录</span>
          <el-tag :type="statusTagMap[record.status] || 'info'" size="small">
            {{ record.status }}
          </el-tag>
        </div>
        <div class="card-content">
          <div class="info-row">
            <span><el-icon><User /></el-icon> {{ record.doctor }}医生</span>
            <span><el-icon><Calendar /></el-icon> {{ formatDate(record.visitDate) }}</span>
          </div>
          <div class="chief-complaint">
            <strong>主诉：</strong>{{ truncateText(record.chiefComplaint, 50) }}
          </div>
        </div>
      </el-card>

      <el-empty v-if="filteredRecords.length === 0" description="暂无病历记录" />
    </div>

    <!-- 病历详情对话框 -->
    <el-dialog
        v-model="detailVisible"
        :title="`${currentRecord.department}就诊记录`"
        width="80%"
        top="5vh"
    >
      <div class="record-detail">
        <div class="detail-header">
          <div class="patient-info">
            <span><strong>就诊日期：</strong>{{ formatDateTime(currentRecord.visitDate) }}</span>
            <span><strong>主治医生：</strong>{{ currentRecord.doctor }}</span>
          </div>
          <div class="record-meta">
            <span><strong>病历状态：</strong>
              <el-tag :type="statusTagMap[currentRecord.status] || 'info'" size="small">
                {{ currentRecord.status }}
              </el-tag>
            </span>
          </div>
        </div>

        <el-tabs v-model="activeTab">
          <el-tab-pane label="主诉" name="chiefComplaint">
            <div class="tab-content">
              <pre>{{ currentRecord.chiefComplaint }}</pre>
            </div>
          </el-tab-pane>
          <el-tab-pane label="现病史" name="presentIllness">
            <div class="tab-content">
              <pre>{{ currentRecord.presentIllness }}</pre>
            </div>
          </el-tab-pane>
          <el-tab-pane label="诊断" name="diagnosis">
            <div class="tab-content">
              <pre>{{ currentRecord.diagnosis }}</pre>
            </div>
          </el-tab-pane>
          <el-tab-pane label="治疗方案" name="treatment">
            <div class="tab-content">
              <pre>{{ currentRecord.treatment }}</pre>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="record-actions">
          <el-button type="primary" @click="handleDownload(currentRecord)">
            <el-icon><Download /></el-icon> 下载病历
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  Document,
  Search,
  User,
  Calendar,
  Download
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 数据状态
const records = ref([])
const loading = ref(false)
const searchQuery = ref('')
const detailVisible = ref(false)
const activeTab = ref('chiefComplaint')
const currentRecord = ref({})

// 状态标签映射
const statusTagMap = {
  '已归档': 'success',
  '待完善': 'warning',
  '草稿': 'info'
}

// 模拟患者病历数据
const mockRecords = [
  {
    recordId: 'MR20230001',
    patientName: '张三',
    patientId: 'P10001',
    visitDate: '2023-05-15 10:30',
    department: '内科',
    doctor: '李医生',
    status: '已归档',
    chiefComplaint: '反复上腹痛3个月，加重1周',
    presentIllness: '患者3个月前无明显诱因出现上腹部隐痛，餐后明显，伴反酸、嗳气，无恶心呕吐，无黑便。1周前症状加重，疼痛程度较前明显，影响进食。',
    diagnosis: '1. 慢性胃炎\n2. 胃溃疡',
    treatment: '1. 奥美拉唑20mg bid（早餐前和晚餐前各一次）\n2. 铝碳酸镁咀嚼片1g tid（餐后1小时服用）\n3. 两周后复查胃镜\n4. 避免辛辣刺激性食物，规律饮食'
  },
  {
    recordId: 'MR20230002',
    patientName: '张三',
    patientId: 'P10001',
    visitDate: '2023-06-10 14:15',
    department: '外科',
    doctor: '王医生',
    status: '已归档',
    chiefComplaint: '右膝关节疼痛1月余',
    presentIllness: '患者1月前无明显诱因出现右膝关节疼痛，上下楼梯时加重，休息后可缓解。无外伤史，无红肿热痛。既往有轻度骨关节炎病史。',
    diagnosis: '右膝骨性关节炎（II期）',
    treatment: '1. 塞来昔布200mg qd（疼痛时服用）\n2. 氨基葡萄糖750mg bid\n3. 建议适度运动，控制体重\n4. 3个月后复查'
  }
]

// 计算属性
const filteredRecords = computed(() => {
  if (!searchQuery.value) return records.value
  const query = searchQuery.value.toLowerCase()
  return records.value.filter(record =>
      record.department.toLowerCase().includes(query) ||
      record.doctor.toLowerCase().includes(query) ||
      record.visitDate.toLowerCase().includes(query) ||
      record.chiefComplaint.toLowerCase().includes(query)
  )
})

// 生命周期钩子
onMounted(() => {
  fetchRecords()
})

// 方法
function fetchRecords() {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    records.value = mockRecords
    loading.value = false
  }, 500)
}

function resetSearch() {
  searchQuery.value = ''
}

function viewRecordDetail(record) {
  currentRecord.value = record
  detailVisible.value = true
}

function handleDownload(record) {
  ElMessage.success(`开始下载 ${record.department}就诊记录`)
  // 实际项目中这里调用下载API
}

function formatDate(dateString) {
  return dateString.split(' ')[0]
}

function formatDateTime(dateString) {
  return dateString.replace(' ', '  ')
}

function truncateText(text, length) {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}
</script>

<style scoped>
.patient-records-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-box {
  width: 300px;
}

.record-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 16px;
}

.record-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.record-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.record-title {
  font-weight: bold;
  font-size: 16px;
  flex: 1;
  margin-right: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 13px;
}

.info-row span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.chief-complaint {
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

.record-detail {
  padding: 0 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.patient-info,
.record-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.tab-content {
  margin: 16px 0;
}

.tab-content pre {
  white-space: pre-wrap;
  font-family: inherit;
  line-height: 1.6;
  background: #f9f9f9;
  padding: 16px;
  border-radius: 4px;
  margin: 0;
}

.record-actions {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-box {
    width: 100%;
  }

  .record-list {
    grid-template-columns: 1fr;
  }

  .detail-header {
    flex-direction: column;
  }
}
</style>
